#!/bin/bash

GOLANG_VERSION="1.22.4"
GO_INSTALL_PATH="/usr/local"

GOLANG_PACK_NAME="go${GOLANG_VERSION}.linux-amd64.tar.gz"


color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

determine_user () {
    if [ "$(id -u)" -ne 0 ];then
        color "请以管理员用户运行此脚本." failure
        exit
    fi
}

uncompress_golang_file () {
    if [ -e ${GOLANG_PACK_NAME} ];then
        color "当前路径$(pwd)已找到${GOLANG_PACK_NAME}，解压到${GO_INSTALL_PATH}" success
        tar -xvf "${GOLANG_PACK_NAME}" -C "${GO_INSTALL_PATH}"
    else
        color "当前路径下不存在golang程序包，请先将程序包放到当前目录后再执行此脚本" failure
        exit
    fi
}

config_golang_env () {
    cat > /etc/profile.d/golang.sh <<-EOF
    export GOROOT=${GO_INSTALL_PATH}/go
    export PATH=\$PATH:\$GOROOT/bin
EOF
    # shellcheck disable=SC1091
    source "/etc/profile.d/golang.sh"
    go version && color "已完成go的安装." success
}

main () {
    determine_user
    uncompress_golang_file
    config_golang_env
}

main